﻿/**
 * ...
 * @author Sergey Mamyan
 */

package tx.facebook.core;
import haxe.Http;
import haxe.Md5;
import haxe.xml.Fast;
import tx.json.JSON;

class Request extends Http {
	
	static var callID:Int = 0;

	public var response:Dynamic;
	
	public function new(method:String){
		super(Facebook.REST_SERVER_URL);
		this.setParameter("v", "1.0");
		this.setParameter("api_key", Facebook.API_KEY);
		this.setParameter("call_id", ""+Date.now().getTime());
		this.setParameter("method", method);
		this.setParameter("format", "JSON");
		if (Facebook.SESSION_KEY != null && Facebook.SESSION_KEY.length > 0) {
			this.setParameter("session_key", Facebook.SESSION_KEY);
		}
	}
	
	public function setParam(key:String, value:String):Void {
		setParameter(key, value);
	}
	
	public function getParam(key:String):String {
		return params.get(key);
	}
	
	public function formatSig():Void {
		var pi:Iterator<String> = params.keys();
		var a:Array<String> = new Array<String>();
		while (pi.hasNext()) {
			var p:String = pi.next();
            if (p != 'sig') {
				a.push(p+'='+params.get(p));
			}
		}
		a.sort(function(a:String, b:String):Int {
			if (a == b) {
				return 0;
			}else if (a > b) {
				return 1;
			} else {
				return -1;
			}
		});
		var s:String = a.join('');
		s += Facebook.API_SECRET;
		this.setParameter("sig",Md5.encode(s));
	}
	
	public function call():Void {
		formatSig();
		request(true);
	}
	
	override public function onData(data:String):Void {
		response = JSON.decode(data);
	}
	
}